#include "GL/glut.h"
#include "Skeleton.h"
#include "SkeletonReader.h"
#include "include.h"

Skeleton::Skeleton()
{
	this->textureManager = NULL;
	head = NULL;
	rotation = 0.0;
	skeletonAnimationManager = new SkeletonAnimationManager();
	angleAmplitudeModifier = 0.0;
	lengthAmplitudeModifier = 0.0;
	timeAmplitudeModifier = 1.0;
	size = Vector2D(1.0,1.0);
}

Skeleton::Skeleton(TextureManager * textureManager, char * fileName)
{
	rotation = 0.0;
	size = Vector2D(1.0,1.0);
	this->textureManager = textureManager;
	head = NULL;
	skeletonAnimationManager = new SkeletonAnimationManager();
	angleAmplitudeModifier = 0.0;
	lengthAmplitudeModifier = 0.0;
	timeAmplitudeModifier = 1.0;
	LoadFromFile(fileName);
	printf("Done loading skeleton from file\n");
}

Skeleton::~Skeleton()
{
	if(head)
	{
		delete(head);
		head = NULL;
	}
	if(skeletonAnimationManager)
	{
		delete(skeletonAnimationManager);
		skeletonAnimationManager = NULL;
	}
}
	
bool Skeleton::LoadFromFile(char * fileName)
{
	head = SkeletonReader::LoadFromFile(fileName, skeletonAnimationManager, textureManager, &size);
	if(head)
	{
		return true;
	}
	return false;
}

void Skeleton::SetAnimation(char * animationName, float angleAmplitudeModifier, 
               	  float lengthAmplitudeModifier, float timeModifier)
{
	this->timeAmplitudeModifier = timeModifier;
	if(head)
	{
		//head->SetModifiers(angleAmplitudeModifier, lengthAmplitudeModifier, timeModifier);
		skeletonAnimationManager->SetAnimation(head, animationName);
	}
}
    
void Skeleton::Think(double elapsedTime)
{
	elapsedTime *= timeAmplitudeModifier;
	if(head)
	{
		if(head->CheckAllOrientation())
		{
			skeletonAnimationManager->SetNextPose(head);
		}
		head->Think(elapsedTime);
	}
}
void Skeleton::SetTimeModifier(float timeModifier)
{
	this->timeAmplitudeModifier = timeModifier;
}
void Skeleton::SetDirection(bool facingRight)
{
	this->facingRight = facingRight;
}
void Skeleton::Draw(Vector2D position)
{
	
	glPushMatrix();
	glLoadIdentity();
	glTranslatef(position.x,position.y, 0.0);
	glRotatef(rotation, 0, 0, 1);
	
	if(facingRight)
		glScalef(size.x,size.y,0);
	else
		glScalef(-size.x,size.y,0);
	glDisable(GL_TEXTURE_2D);
	if(head)
		head->Draw();
	glPopMatrix();
}
void Skeleton::RadianRotate(float rotation)
{
	Rotate(rotation * 180.0 / PI);
}
void Skeleton::Rotate(float rotation)
{
	this->rotation += rotation;
	while(this->rotation >= 360.0)
		this->rotation -= 360.0;
	while(this->rotation < 0.0)
		this->rotation += 360.0;
}
